<template>
  <div v-loading="loading">
    <div style="display: flex; align-items: center">
      <i-tabs
        type="card"
        v-model="activeName"
        :tabs="tabs"
        @tab-click="handleClickTabs"
      />
      <span style="color: red">
        {{
          activeName == tabsName.INNER
            ? '内部名单（仅支持免费电站）：名单内人员可充电，名单外人员禁止充电'
            : '免费名单：名单内人员充电免费，名单外人员正常收费'
        }}
      </span>
    </div>
    <TableSearch
      ref="tableSearch"
      :tableBtns="tableBtns"
      :search-path="searchPath"
      :formItemsInline="formItemsInline"
      :columns="columns"
      :tableData="tableData"
      :form="form"
      @handleTableData="handleTableData"
      @reset="reset"
      :key="resetKey"
    />
    <AddWhiteListDlg
      v-if="dlgVisible"
      :visible.sync="dlgVisible"
      :type="dlgType"
      :listType="activeName"
      @refreshTable="refresh"
    />
  </div>
</template>
<script>
const tabsName = {
  INNER: 0, // 内部名单
  FREE: 1, // 免费名单
}

import TableSearch from '@/components/TableSearch'
import {
  selectFreeInfoPageList,
  selectInternalInfoPageList,
  deleteFreeListInfo,
  deleteInternalListInfo,
  exportFreeListInfo,
  exportInternalListInfo,
} from '@/api/user'
import AddWhiteListDlg from './Dialogs/AddWhiteListDlg'
import formatter from '@/utils/format'

const dateTypeMap = {
  1: '每天',
  2: '每周',
  3: '每月',
  4: '每年',
}
export default {
  name: 'WhiteList',
  components: { TableSearch, AddWhiteListDlg },
  mounted() {
    this.loading = true
  },
  data() {
    return {
      tabsName,
      loading: false,
      activeName: 0,
      resetKey: 0,
      dlgVisible: false,
      dlgType: '',
      stationList: [],
      tabs: [
        {
          label: '内部名单',
          name: dateTypeMap.INNER,
        },
        {
          label: '免费名单',
          name: dateTypeMap.FREE,
        },
      ],
      tableBtns: [
        {
          label: '导出',
          icon: 'el-icon-download',
          isExport: true,
          startDownload: (callback) => {
            let handler = () => {}
            if (this.activeName == tabsName.INNER) {
              handler = exportInternalListInfo
            } else {
              handler = exportFreeListInfo
            }

            handler({
              ...this.form,
              pageSize: 10,
              currentPage: 1,
            })
              .then((res) => {
                callback(res)
              })
              .catch((err) => {
                console.log(err)
              })
          },
          resourceId: '/web/user-management/chargewhitelist-management/导出',
        },
        {
          label: '添加',
          icon: 'el-icon-plus',
          click: () => {
            this.dlgVisible = true
            this.dlgType = 'add'
          },
          resourceId: '/web/user-management/chargewhitelist-management/添加',
        },
        {
          label: '批量添加',
          icon: 'el-icon-plus',
          click: () => {
            this.dlgVisible = true
            this.dlgType = 'batchAdd'
          },
          resourceId:
            '/web/user-management/chargewhitelist-management/批量添加',
        },
        {
          label: '批量删除',
          click: () => {
            this.dlgVisible = true
            this.dlgType = 'batchDelete'
          },
          icon: 'el-icon-delete',
          resourceId:
            '/web/user-management/chargewhitelist-management/批量删除',
        },
        {
          label: '模板下载',
          isDownload: true,
          href: require('../../assets/batchTemplate/批量导入内部白名单模板.xlsx'),
          fileName: '批量导入内部白名单模板',
          resourceId:
            '/web/user-management/chargewhitelist-management/模板下载',
        },
      ],
      searchPath: '/web/user-management/chargewhitelist-management/查询',
      formItemsInline: [
        {
          placeholder: '请输入手机号',
          type: 'text',
          clearable: true,
          value: 'mobile',
          resourceId: '/web/user-management/chargewhitelist-management/手机号',
        },
        {
          placeholder: '电站名称',
          type: 'text',
          clearable: true,
          value: 'stationName',
          resourceId:
            '/web/user-management/chargewhitelist-management/适用电站',
        },
      ],
      columns: [
        {
          label: '添加日期',
          prop: 'createTime',
          formatter,
          resourceId:
            '/web/user-management/chargewhitelist-management/添加时间',
        },
        {
          label: '姓名',
          prop: 'userName',
          resourceId: '/web/user-management/chargewhitelist-management/姓名',
        },
        {
          label: '手机号',
          prop: 'mobile',
          resourceId: '/web/user-management/chargewhitelist-management/手机号',
        },
        {
          label: '适用电站',
          prop: 'stationName',
          resourceId:
            '/web/user-management/chargewhitelist-management/适用电站',
        },
        {
          label: '时长限制(h)',
          prop: 'initialTime',
          resourceId:
            '/web/user-management/chargewhitelist-management/时长限制(h)',
          formatter: (row) => {
            return row.initialTime || '--'
          },
        },
        {
          label: '剩余时长(min)',
          prop: 'restTime',
          resourceId:
            '/web/user-management/chargewhitelist-management/剩余时长(min)',
          formatter: (row) => {
            return row.restTime || '--'
          },
        },
        {
          label: '限制周期',
          formatter: (item) => {
            return item.date ? dateTypeMap[item.date] : '--'
          },
          resourceId:
            '/web/user-management/chargewhitelist-management/限制周期',
        },
        {
          label: '操作',
          resourceId: '/web/user-management/chargewhitelist-management/操作',
          buttons: [
            {
              label: '删除',
              class: 'table-button-red',
              click: (row) => {
                let confirmTitle = ''
                let handler = () => {}

                if (this.activeName == tabsName.INNER) {
                  confirmTitle = '内部名单'
                  handler = deleteInternalListInfo
                } else {
                  confirmTitle = '免费名单'
                  handler = deleteFreeListInfo
                }

                this.$confirm(
                  `是否要将用户从${confirmTitle}中删除?`,
                  '删除用户',
                  {
                    center: true,
                    customClass: 'tip-dialog__wrapper',
                  }
                ).then(() => {
                  this.loading = true
                  handler({
                    stationId: row.stationId,
                    mobile: row.mobile,
                  })
                    .then(() => {
                      this.$message({
                        showClose: true,
                        message: '删除成功',
                        type: 'success',
                      })

                      this.$refs.tableSearch.refreshTable()
                    })
                    .catch((err) => {
                      console.log(err)
                    })
                    .finally(() => {
                      this.loading = false
                    })
                })
              },
              resourceId:
                '/web/user-management/chargewhitelist-management/删除',
            },
          ],
        },
      ],
      tableData: {},
      form: {},
    }
  },
  methods: {
    handleClickTabs() {
      this.form = {}

      let index = this.tableBtns.findIndex((item) => item.label == '模板下载')

      if (index > -1) {
        let href = ''
        let fileName = ''
        if (this.activeName == tabsName.INNER) {
          href = require('../../assets/batchTemplate/批量导入内部白名单模板.xlsx')
          fileName = '批量导入内部白名单模板'
        } else {
          href = require('../../assets/batchTemplate/批量导入免费白名单模板.xlsx')
          fileName = '批量导入免费白名单模板'
        }
        this.$set(this.tableBtns, index, {
          ...this.tableBtns[index],
          href,
          fileName,
        })
      }

      this.$nextTick(() => {
        this.$refs.tableSearch.refreshTable()
      })
    },
    handleTableData(params) {
      this.loading = true
      if (this.activeName == tabsName.INNER) {
        selectInternalInfoPageList(params)
          .then((res) => {
            this.tableData = {
              list: res.list,
              totalCount: res.totalAmount,
            }
          })
          .catch((err) => {
            console.log(err)
          })
          .finally(() => {
            this.loading = false
          })
      } else {
        selectFreeInfoPageList(params)
          .then((res) => {
            this.tableData = {
              list: res.list,
              totalCount: res.totalAmount,
            }
          })
          .catch((err) => {
            console.log(err)
          })
          .finally(() => {
            this.loading = false
          })
      }
    },
    refresh() {
      this.$refs.tableSearch.refreshTable()
    },
    reset() {
      this.form = {}
    },
  },
}
</script>
<style lang="scss" scoped></style>
